<?php

namespace App\Http\Controllers\Wx;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Modules\Manager\Entities\Manager;

class GetUserController extends WxCommonController
{
    use ResponseData;
    public function getUser(Manager $model){
        $user = session('wechat.oauth_user.default'); // 拿到授权用户资料
        if(isset($user['id'])){
            $openid = $user['id'];
        }
        if($openid){
            info('走到已绑定关系');
            $student = Manager::query()->where('wechat_openid',$openid)->first();
            if($student){
                return view('binding', ['user' => $student]);
            }else{
                $data = [
                    'wechat_openid'=>$openid,
                    'nick_name'=>$user['name']?$user['name']:'',
                    'avatar'=>$user['avatar']?$user['avatar']:'',
                ];
                $model->fill($data);
                $model->save();
                return view('binding', ['user' => $model]);
            }
        }else{
            return $this->failed('未获取到openid');
        }
    }
    // 绑定用户手机号
    public function bindUser(Request $request,Manager $model){
        if(!$request->filled('openid')){
            return $this->failed('请填写openid',201);
        }
        if(!$request->filled('phone')){
            return $this->failed('请填写手机号',201);
        }
        // 已存在用户
        $isPhone = $model->where('phone',$request->phone)->first();
        if($isPhone){
            $delete = $model->replicate()->where('wechat_openid',$request->openid)->first();
            $isPhone->wechat_openid = $request->openid;
            $isPhone->avatar = $delete->avatar;
            $isPhone->nick_name = $delete->nick_name;
            $res = $delete->delete();
            if($res){
                $isPhone->save();
            }
            return $this->success('换绑成功');
        }
        $user = $model->replicate()->where('wechat_openid',$request->openid)->first();
        if(!$user){
            return $this->failed('未找到该用户',201);
        }
        $user->phone = $request->phone;
        $user->save();
        return $this->success('绑定成功!');

    }
    public function getAuth(){
        $user = session('wechat.oauth_user.default');

        return 1;
    }

}
